import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/',
    component: () => import('@/layout/MainLayout.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '首页', icon: 'home' }
      },
      {
        path: 'bread',
        name: 'Bread',
        component: () => import('@/views/bread/Index.vue'),
        meta: { title: '面包管理', icon: 'fast-food' }
      },
      {
        path: 'sales',
        name: 'Sales',
        component: () => import('@/views/sales/Index.vue'),
        meta: { title: '销售管理', icon: 'cart' }
      },
      {
        path: 'sales/create',
        name: 'SalesCreate',
        component: () => import('@/views/sales/Create.vue'),
        meta: { title: '销售登记', hidden: true }
      },
      {
        path: 'sales/log',
        name: 'SalesLog',
        component: () => import('@/views/sales/Log.vue'),
        meta: { title: '销售日志', icon: 'document-text' }
      },
      {
        path: 'employee',
        name: 'Employee',
        component: () => import('@/views/employee/Index.vue'),
        meta: { title: '员工管理', icon: 'people', role: 'MANAGER' }
      },
      {
        path: 'stock',
        name: 'Stock',
        component: () => import('@/views/stock/Index.vue'),
        meta: { title: '库存管理', icon: 'archive' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  if (to.path !== '/login' && !userStore.token) {
    next('/login')
  } else if (to.path === '/login' && userStore.token) {
    next('/')
  } else {
    // 检查角色权限
    if (to.meta.role && userStore.userInfo?.role !== to.meta.role) {
      next('/')
      return
    }
    next()
  }
})

export default router

